import axios, {
  AxiosError,
  AxiosResponse,
  Method,
  RawAxiosRequestHeaders,
} from "axios";
import {
  Toast,
} from "antd-mobile";
// 路由
const BASEURL = process.env.NODE_ENV === "development" ? "/api" : "/api";

// const headers = { "x-auth-token": "59cd7e905a0a80fb2737ca6355eb09c7" };
// const headers: any["x-auth-token"] = "59cd7e905a0a80fb2737ca6355eb09c7";
// console.log(headers);

export default function (
  url: string,
  // POST 请求体
  data: object,
  // GET URL参数
  //   params: object,
  headers: RawAxiosRequestHeaders,
  // 默认POST
  method: Method = "POST"
) {
  return new Promise<any>((resolve, reject) => {
    axios({
      url: BASEURL + url,
      method: method,
      headers: headers,
      // params:params,
      params: method === "GET" ? data : null,
      data: method === "POST" ? data : null,
      responseType: "json",
    })
      .then((res: AxiosResponse<any, any>) => {
        // 统一处理code = 0
        if(res.data.code == 0) {
          resolve(res.data);
        } else if (res.data.code == 2006) {
          resolve(res.data);
        } else {
          // Toast.show({ content: res.data.msg, icon: "fail" });
          // localStorage.removeItem("encryptedUserToken");
          reject(res.data);
        }
      })
      .catch((err: AxiosError<any, any>) => {
        if (err.response?.data.code !== 0) {
          console.log("跳转到登录页");
        }

        reject(err);
      });
  });
}
